package com.tiance.utils;

import com.tiance.common.OperationEnvironment;
import com.tiance.constants.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2018/12/21
 *
 * Description：
 *
 * Modification History:
 *
 */
public class EnvironmentUtil {

    private static OperationEnvironment opEnv = new OperationEnvironment();

    public static OperationEnvironment getEnv() {
        OperationEnvironment env = new OperationEnvironment();
        env.setClientId(CommonConstants.APP_NAME);
        opEnv.setClientIp(getHostIP());
        env.setClientMac(MDC.get(CommonConstants.SESSION_ID));
        return env;
    }

    /**
     * 获得本机ip
     * @return
     */
    private static String getHostIP() {
        String machineIp = null;
        try {
            machineIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        return StringUtils.isBlank(machineIp)?"":machineIp;
    }

    public static String getIP(HttpServletRequest request){
        String ip=request.getHeader("x-forwarded-for");
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("X-Real-IP");
        }
        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getRemoteAddr();
        }
        return ip;
    }

}
